<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-09-23 17:35:06
 * @LastEditTime : 2020-02-20 16:14:20
 * @LastEditors  : Please set LastEditors
-->
<template>
    <div>
        <div class="headerBtn1">
            <!-- <Button type="primary"  style="position:relative;z-index:55" @click="opeartionManyVm">批量操作虚拟机</Button> -->
            <Input suffix="ios-search" placeholder="虚拟机名称" search v-model="virtualNameOfReach" @on-search="vmCurrentPage=1;getVmListManage()"  @on-change="vmCurrentPage=1;limitingReach()" clearable  style="width: auto;position:relative;z-index:55" />
            <Input suffix="ios-search" placeholder="IP" search  v-model="virtualIPOfReach"  @on-search="vmCurrentPage=1;getVmListManage()"  @on-change="vmCurrentPage=1;limitingReach()" clearable  style="width: auto;position:relative;z-index:55"/>
            <!-- <Input suffix="ios-search" placeholder="Enter Mac" search v-model="virtualMacOfReach"  @on-search="vmCurrentPage=1;getVmListManage()"  @on-change="vmCurrentPage=1;limitingReach()" clearable  style="width: auto;position:relative;z-index:55" v-show="controlSearchBtn"/> -->
            <Input suffix="ios-search" placeholder="镜像名称" search v-model="virtualImageNameOfReach"  @on-search="vmCurrentPage=1;getVmListManage()"  @on-change="vmCurrentPage=1;limitingReach()" clearable  style="width: auto;position:relative;z-index:55" v-show="controlSearchBtn"/>
            <!-- <Cascader :data="vmAttributeData"    change-on-select @on-change="listenKeyChange" style="display:inline-block" placeholder="请选择key/value" @on-visible-change="getVmAttributeKey" v-show="controlSearchBtn"></Cascader> -->
            <Select filterable  v-model="virtualSystypeOfReach" filterable  style="width:180px;" clearable placeholder="请选择系统类型" @on-change="vmCurrentPage=1;getVmListManage()" v-show="controlSearchBtn">
                <Option value="linux">Linux</Option>
                <Option value="windows">Windows</Option>
                <!-- <Option value="mac">Mac</Option> -->
                <Option value="unix">Unix</Option>
            </Select>
            <Select filterable  v-model="virtualvmTypeOfReach" filterable  style="width:180px;" clearable placeholder="请选择虚拟机类型" @on-change="vmCurrentPage=1;getVmListManage()" v-show="controlSearchBtn">
                <Option value="VM">VM</Option>
                <Option value="SERVER">SERVER</Option>
                <Option value="CLIENT">CLIENT</Option>
                <Option value="DRT">DRT</Option>
                <Option value="IDS">IDS</Option>
                <Option value="DES">DES</Option>
                <Option value="WAF">WAF</Option>
                <Option value="FW">FIREWALL</Option>
                <Option value="PRT">PRT</Option>
            </Select>
            <!-- <Select filterable v-model="virtualNetworkIdOfReach" filterable  style="width:180px;" clearable placeholder="请选择Network"  @on-open-change="reachNetworkList"  @on-change="vmCurrentPage=1;getVmListManage()">
                <Option v-for="(item,index) in networkData" :key="index" :value="item.networkId">{{item.networkName}}</Option>
            </Select> -->
            <Button type="primary" @click="vmCurrentPage=1;getVmListManage()" style="position:relative;z-index:55">搜索</Button>
            <Button type="dashed"  @click="controlSearch" :icon="controlSearchImage">{{controlSearchText}}</Button>
        </div>
        <Table border ref="selection" :columns="vmColumnsData" :data="vmListDataTable" :stripe="true" :show-header="true"  id="vmListTable" :height="tableHeight" @on-selection-change="selectTableData" :loading="loadingTable" @on-select="test"></Table>
        <Page :total="vmTotal" show-elevator :current="vmCurrentPage" :page-size="vmItemPage" 
        :show-total= true   class-name="pageStyle1"  @on-change="switchineVmCurrentPage" 
        @on-page-size-change="switchVmItemPage" :page-size-opts="pageItemGroup"/>
        <!-- 虚拟机元数据 -->
        <Modal
            v-model="vmMetadata"
            title="元数据"
            ok-canel = "关闭"
            ok-text = "确定"
            :loading = "vmMetadataLoading"
            @on-cancel="cancel"
            @on-ok="SaveMetaData"
        >
            <Tag type="dot"  color="primary" >虚拟机：{{vmName}}</Tag>
            <div v-for="(item,key) in metadataData" :key="key" style="margin:5px 0px;text-align:left;position:relative;width:101%">
                <Input placeholder="Enter key" style="width: 226px" v-model="item.key" clearable></Input>
                <Icon type="md-remove" />
                <Input placeholder="Enter value" style="width: 220px" v-model="item.value" clearable></Input>
                <Icon type="md-remove-circle" @click="removeMetadata(key)" :size="20" style="cursor:pointer"/>
            </div>
            <div >
                <Button class="md-add-jh" type="dashed" size="large" @click="handleAddMetadata" >添加元数据</Button>
            </div>
        </Modal>
        <!-- 批量操作虚拟机面板 -->
        <Modal v-model="vmManyPanel" width="371">
            <p slot="header" style="text-align:left">
                <span>共选择了{{vmManyNumber}}台虚拟机</span>
            </p>
            <div>
                <Poptip
                    v-for="(item,index) in btnData" :key="index"
                    confirm
                    title="您确定要执行此操作吗?"
                    @on-ok="okVm(item)"
                    @on-cancel="cancel">
                    <Button  type="primary" style="margin:5px;">{{item}}</Button>
                </Poptip>
            </div>
            <div slot="footer">
                <Button type="primary" @click="vmManyPanel = false">关闭</Button>
            </div>
        </Modal>
        <!-- 端口转发列表 -->
        <Modal v-model="portListPanel" width="1200">
            <p slot="header" style="font-size:14px;text-align:left">
                <span>虚拟机：{{vmName}}</span>
            </p>
            <div style="text-align:center">
                <div style="text-align:left;margin-bottom:10px">
                    <Button type="primary" style="margin:5px;" @click="openPortPanel">开放端口</Button>
                </div>
                <Table border ref="selection" :columns="portTableCloums" :data="portTableData"  :stripe="true" :show-header="true" ></Table>
            </div>
            <div slot="footer">
                <Button type="primary" @click="portListPanel = false" >关闭</Button>
            </div>
        </Modal>
        <!-- 转发端口 -->
        <Modal
            v-model="openPort"
            title="添加"
            ok-canel = "关闭"
            ok-text = "确定"
            width="380"
            :loading = "addPortLoading"
            @on-cancel="cancel"
            @on-ok="addPort"
        >
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="类型" prop="type">
                    <RadioGroup v-model="formValidate.type" @on-change="listenTypeChange">
                        <Radio label="ssh"></Radio>
                        <Radio label="rdp"></Radio>
                        <Radio label="vnc">vnc</Radio>
                        <Radio label="other"></Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="other" prop="customType" v-if="disabledType">
                    <Input v-model="formValidate.customType" style="width:200px" placeholder="请输入其他类型"></Input>
                </FormItem>
                <FormItem label="端口" prop="port">
                    <input-number :min="1" :value="1" :max="65534" v-model="formValidate.port" style="width:200px"></input-number>
                </FormItem>
                <FormItem label="协议" prop="protocol">
                    <RadioGroup v-model="formValidate.protocol">
                        <Radio label="tcp">TCP</Radio>
                        <Radio label="udp" :disabled="disabledprototol">UDP</Radio>
                        <Radio label="icmp" :disabled="disabledprototol">ICMP</Radio>
                    </RadioGroup>
                </FormItem>
            </Form>
        </Modal>
        <!-- 接入选择页面 -->
        <Modal 
            v-model="selectDataPanel" 
            title="选择接入的IP"
            ok-canel = "关闭"
            ok-text = "接入"
            width="380"
            :loading = "selectDataPanelLoading"
            @on-cancel="cancel"
            @on-ok="vmAccessChage"
        >
            <div>
                <RadioGroup  v-model="accessVmIp" v-for="(item,index) in selectDataGroup" :key="index" @on-change="changeIpAccess">
                    <Radio  :label="item.ip">{{item.ip}}</Radio>
                </RadioGroup>
            </div>
        </Modal>
        <!-- 页面loading -->
        <Spin fix v-show="isSpinShow">
            <Icon type="load-c" size="30" class="demo-spin-icon-load"></Icon>
            <div>Loading...</div>
        </Spin>
        <!--修改密码-->
        <Modal 
            v-model="passwordModal.show" 
            title="修改密码"
            width="380"
            :loading = "passwordModal.loading"
            @on-cancel="cancel"
            @on-ok="changePassword"
        >
            <div>
                密码：<Input v-model="vmPassword" style="width:200px" placeholder="请输入密码"></Input>
            </div>
        </Modal>
    </div>    
</template>
    
<script>
    import axios from '@/libs/axios1'
    import $ from 'jquery'
    import cookieUse from '@/libs/cookie.js'
    import { mapState } from 'vuex'

    export default {
        name:'devices',
        computed: {
            ...mapState(['cloudType']),
        },
        data(){
            return {
                // 接收的id
                scenarioId:this.$route.query.id,
                currentProjectId:this.$route.query.projectId,
                pageItemGroup:[10,20],
                isSpinShow:false,
                loadingTable:true,
                vmManyPanel:false,
                vmManyNumber:'',
                vmName:'',
                vmMetadata:false,
                vmMetadataLoading:true,
                metadataData:[
                    {
                        key:'',
                        value:''
                    },
                ],
                projectName:'',
                vmTotal:0,
                vmCurrentPage:1,
                vmItemPage:10,
                vmColumnsData:[
                    // {
                    //     type: 'selection',
                    //     width: 60,
                    //     align: 'center',
                    //     "fixed": "left",
                    // },
                    {
                        type: 'index',
                        width: 60,
                        align: 'center',
                        "fixed": "left",
                    },
                    {
                        title:'虚拟机名称',
                        key:'name',
                        align: 'center',
                        sortable: true,
                        minWidth:120,
                        "fixed": "left",
                    },
                    {
                        title:'网络名称',
                        key:'networkName',
                        align: 'center',
                        minWidth:120,
                        "fixed": "left",
                    },
                    {
                        title:'网络信息',
                        key:'',
                        align:'center',
                        children:[
                            {
                                title:'CIDR',
                                key:'',
                                align:'center',
                                minWidth:200,
                                render:(h,params)=>{
                                    let _this = this;
                                    params = params.row;
                                    let addresses = [];
                                    if(params.addresses){
                                        if(params.addresses.length!=0){
                                            addresses = params.addresses.map((item)=>{
                                                let cidr = item.ips.map(ip => {
                                                    return h('div',{},ip.cidr);
                                                })
                                                return h('div',{},cidr);
                                            })
                                        }
                                    }
                                     return h('div',{},addresses)
                                }
                            },
                            {
                                title:'IP',
                                key:'',
                                align:'center',
                                sortable: true,
                                minWidth:200,
                                render:(h,params)=>{
                                    let _this = this;
                                    params = params.row;
                                    let addresses = [];
                                    if(params.addresses){
                                        if(params.addresses.length!=0){
                                            addresses = params.addresses.map((item)=>{
                                                let ips = item.ips.map(ip => {
                                                    return h('div',{},ip.ipAddress);
                                                })
                                                return h('div',{},ips);
                                            })
                                            return h('div',{},addresses)
                                        }
                                    }
                                }
                            },
                            {
                                title:'Mac',
                                key:'',
                                align:'center',
                                minWidth:200,
                                render:(h,params)=>{
                                    let _this = this;
                                    params = params.row;
                                    let addresses = [];
                                    if(params.addresses){
                                        if(params.addresses.length!=0){
                                            addresses = params.addresses.map((item)=>{
                                                return h('div',{},item.macAddress);
                                            })
                                            return h('div',{},addresses)
                                        }
                                    }
                                }
                            },
                            {
                                title:'Version',
                                key:'',
                                align:'center',
                                minWidth:200,
                                render:(h,params)=>{
                                    let _this = this;
                                    params = params.row;
                                    let addresses = [];
                                    if(params.addresses){
                                        if(params.addresses.length!=0){
                                            addresses = params.addresses.map((item)=>{
                                                let ipVersion = item.ips.map(ip => {
                                                    return h('div',{},ip.ipVersion);
                                                })
                                                return h('div',{},ipVersion);
                                            })
                                            return h('div',{},addresses)
                                        }
                                    }
                                }
                            }
                        ]
                    },
                    {
                        title:'接入信息',
                        key:'AccessInformation',
                        align: 'center',
                        minWidth:600,
                        children:[
                            {
                                title: '用户名',
                                key: 'ausernamege',
                                align: 'center',
                                minWidth:150,
                                render:(h,params)=>{
                                    let _this = this;
                                    params = params.row;
                                    let userNameGroup = [];
                                    if(params.accesses){
                                        if(params.accesses.length!=0){
                                            userNameGroup = params.accesses.map((item)=>{
                                                return h('div',{},item.username)
                                            })
                                        }
                                    }
                                    return h('div',{},userNameGroup)
                                }
                            },
                            {
                                title: '密码',
                                key: 'password',
                                align: 'center',
                                minWidth:150,
                                render:(h,params)=>{
                                    let _this = this;
                                    params = params.row;
                                    let userNameGroup = [];
                                    if(params.accesses){
                                        if(params.accesses.length!=0){
                                            userNameGroup = params.accesses.map((item)=>{
                                                return h('div',{},item.password)
                                            })
                                        }
                                    }
                                    return h('div',{},userNameGroup)
                                }
                            },
                            {
                                title: '接入类型',
                                key: 'accessType',
                                align: 'center',
                                minWidth:150,
                                render:(h,params)=>{
                                    let _this = this;
                                    params = params.row;
                                    let userNameGroup = [];
                                    if(params.accesses){
                                        if(params.accesses.length!=0){
                                            userNameGroup = params.accesses.map((item)=>{
                                                return h('div',{},item.accessType)
                                            })
                                        }
                                    }
                                    return h('div',{},userNameGroup)
                                }
                            },
                            {
                                title: 'PlugInType',
                                key: 'plugInType',
                                align: 'center',
                                minWidth:150,
                                render:(h,params)=>{
                                    let _this = this;
                                    params = params.row;
                                    let userNameGroup = [];
                                    if(params.accesses){
                                        if(params.accesses.length!=0){
                                            userNameGroup = params.accesses.map((item)=>{
                                                return h('div',{},item.plugInType)
                                            })
                                        }
                                    }
                                    return h('div',{},userNameGroup)
                                }
                            },
    
                        ],
                    },
                    {
                        title:'系统类型',
                        key:'sysType',
                        minWidth: 150,
                        align: 'center',
                        filters: [
                                {
                                    label: 'Linux',
                                    value: 'linux'
                                },
                                {
                                    label: 'Windows',
                                    value: 'windows'
                                },
                                // {
                                //     label: 'Mac',
                                //     value: 'mac'
                                // },
                                {
                                    label: 'Unix',
                                    value: 'unix'
                                }
                            ],
                        filterMethod (value, row) {
                            return row.sysType ==value;
                        }
                    },
                    {
                        title:'镜像名称',
                        key:'imageName',
                        minWidth: 150,
                        align: 'center'
                    },
                    // {
                    //     title:'HostInformation',
                    //     key:'',
                    //     align:'center',
                    //     children:[
                    //         {
                    //             title:'Host',
                    //             key:'host',
                    //             align:'center',
                    //             minWidth:150,
                    //         },
                    //         {
                    //             title:'HostIP',
                    //             key:'hostIp',
                    //             align:'center',
                    //             sortable: true,
                    //             minWidth:150,
                    //         },
                    //     ]
                    // },
                    {
                        title:'资源信息',
                        key:'',
                        align:'center',
                        children:[
                            {
                                title:'CPU',
                                key:'cpu',
                                sortable: true,
                                align:'center',
                                minWidth:120,
                            },
                            {
                                title:'DISK(/GB)',
                                key:'disk',
                                sortable: true,
                                align:'center',
                                minWidth:120,
                            },
                            {
                                title:'RAM(/MB)',
                                key:'ram',
                                sortable: true,
                                align:'center',
                                minWidth:120,
                            },
                        ]
                    },
                    {
                        title:'虚拟机类型',
                        key:'vmType',
                        minWidth: 100,
                        align: 'center'
                    },
                    {
                        title:'虚拟化类型',
                        key:'vzType',
                        minWidth: 100,
                        align: 'center',
                        filters: [
                            {
                                label: 'kvm',
                                value: 'kvm'
                            },
                            {
                                label: 'docker',
                                value: 'docker'
                            }
                        ],
                        filterMultiple: false,
                        filterMethod (value, row) {
                            console.log(value)
                            if (value == 'kvm') {
                                return row.vzType=="kvm";
                            } else if (value == 'docker') {
                                 return row.vzType=="docker";
                            }else{
    
                            }
                        }
                    },
                    {
                        title:'创建时间',
                        key:'created',
                        align: 'center',
                        sortable: true,
                        minWidth:150,
                    },
                    {
                    title:'接入操作',
                    key:'2',
                    align: 'center',
                    width:200,
                    fixed:'right',
                    render:(h,params)=>{
                        let _this = this;
                        params = params.row;
                        let accessGroup = [];
                        if(params.accesses){
                            if(params.accesses.length!=0){
                                accessGroup = params.accesses.map(item=>{
                                    if(item.accessType == 'vnc'){
                                        return 'vnc'
                                    }else{
                                        return item.accessType;
                                    }
                                })
                            }
                        }
                        accessGroup.push("console");
                        function dedupe(array){
                            return Array.from(new Set(array));
                        }
                        accessGroup = dedupe(accessGroup)
                        let SelectGroup = [];
                        SelectGroup = accessGroup.map((element,index)=>{
                            if(index==0){
                                return;
                            }
                            return h('Option',{
                                props:{
                                    value:element
                                }
                            },element)
                        });
                        SelectGroup.unshift(h('Option',{
                            props:{
                                value:'0'
                            },
                            class:['emptyAccess'],
                            style:{
                                display:'none'
                            }
                        },''))
                        return h('div',{
                            class:['accessType'],
                        },[
                            h('Icon',{
                                props:{
                                    type:'md-refresh',
                                },
                                attrs:{
                                    title:'刷新接入连接'
                                },
                                on:{
                                    click(event){
                                        _this.loadingTable = true
                                        _this.deleteAccessAisle(params.id)
                                    }
                                },
                                style:{
                                    fontSize:'20px',
                                    marginRight:'10px',
                                    cursor:'pointer'
                                },
                            },'')
                            ,
                            h('Button',{
                                props:{
                                    type:'primary',
                                    'label':'000',
                                },
                                on:{
                                    click(evt){
                                        let e = window.event || evt;
                                        _this.selectDataGroup = [];
                                        _this.accessVmType = e.srcElement.innerText;
                                        _this.accessVmId = params.id;
                                        _this.accessVmIp = '';
                                        for (let index = 0; index < params.addresses.length; index++) {
                                            if(params.addresses[index].version==4){
                                                _this.selectDataGroup.push(params.addresses[index])
                                            }
                                        }
                                        if(_this.selectDataGroup.length>1){
                                            if(e.srcElement.innerText=="ssh"||e.srcElement.innerText=="rdp"){
                                                _this.selectDataPanel = true;
                                            }else{
                                                _this.loadingTable = true;
                                                _this.vmAccess(params.id,e.srcElement.innerText)
                                            }
                                        }else{
                                            _this.loadingTable = true;
                                            _this.vmAccess(params.id,e.srcElement.innerText)
                                        }
                                    }
                                },
                                style:{
                                    borderRadius:'4px 0px 0px 4px'
                                },
                            },accessGroup[0]),
                            h('Select',{
                                props:{
                                    placeholder:'',
                                    transfer:true,
                                },
                                style:{
                                    width:'20px'
                                },
                                on:{
                                    'on-change':(value)=>{
                                        $('.emptyAccess').click();
                                        if(value!=0){
                                            _this.vmAccess(params.id,value)
                                        }
                                        $('.accessType .ivu-select-placeholder').text("")
                                    }
                                }
                            },SelectGroup)
                        ])
    
                    }
                    },
                    {
                        title:'操作',
                        key:'',
                        align: 'center',
                        minWidth:150,
                        fixed:'right',
                        render:(h,params)=>{
                            let _this = this;
                            params = params.row;
                            let statusVm ="";
                            if(_this.vmGroupStatus.length!=0){
                                _this.vmGroupStatus.forEach(element => {
                                    if(element.id==params.id){
                                        if(element.enableCrash){
                                            statusVm = "MELT"
                                        }else{
                                            statusVm =  element.status;
                                        }
                                    }
                                });
                            }
                            // let statusVm = _this.vmGroupStatus[_this.vmIdGroupStatus.findIndex(params.id)]
                            let operationGroup = ["监控"];
                            let operationOption = [];
                            switch (statusVm) {
                                case "ACTIVE":
                                    operationGroup = ["关机","重启","重置","挂起","暂停"]
                                    operationGroup.push("密码");  // ,"元数据","端口转发"
                                    break;
                                case "Running":
                                    operationGroup = ["关机","重启","重置","挂起","暂停"]
                                    operationGroup.push("密码"); // ,"元数据","端口转发"
                                    break;
                                case "SHUTOFF":
                                    operationGroup = ["开机","重置"]
                                    operationGroup.push("密码");  // ,"元数据","端口转发"
                                    break;
                                case "DOWN":
                                    operationGroup = ["开机","重置"]
                                    break;
                                case "Stopped":
                                    operationGroup = ["开机","重置"]
                                    break;
                                case "SUSPENDED":
                                    operationGroup = ["拯救"]
                                    operationGroup.push("密码"); // ,"元数据","端口转发"
                                    break;
                                case "ERROR":
                                    operationGroup = ["重启","重置状态"]
                                    break;
                                case "PAUSED":
                                    operationGroup = ["取消暂停"]
                                    operationGroup.push("密码"); // ,"元数据","端口转发"
                                    break;
                                case "CRUSH"://虚拟机奔溃状态
                                    operationGroup = ["关机","重启"]
                                    break;
                                case "PASSWORD"://虚拟机未知状态
                                    operationGroup = ["关机"]
                                    break;
                                case "MELT"://虚拟机奔溃状态
                                    operationGroup = ["重启","重置"]
                                    break;
                                default:
                                    operationGroup = ["关机"]
                                    break;
                            }
                            operationOption = operationGroup.map((item,index)=>{
                                if(index==0){
                                    return h('Option',{props:{value:0,label:0},class:['falseValue'+params.id],style:{display:'none'}},'')
                                }else{
                                    return h('Option',{props:{value:item}},item)
                                }
                            })
                            
                            return h('div',{
                                class:['opertionVm'],
                            },[h('Button',{
                                 props:{
                                    type:'primary',
                                    
                                },
                                on:{
                                    click(event){
                                        let value = operationGroup[0];
                                        if(value=="密码"||value=="元数据"||value=="端口转发"){
                                            _this.vmSwitchTypeOperation(params.id,value,params)
                                        }else{
                                            _this.vmSwitchTypeOperation(params.id,value,params)
                                        }
                                    }
                                },
                                style:{
                                    borderRadius:'4px 0px 0px 4px'
                                },
                            },operationGroup[0]),h('Select',{
                                props:{
                                    placeholder:'',
                                    value:0,
                                    transfer:true
                                },
                                style:{
                                    width:'20px'
                                },
                                class:['ssssssssss'],
                                on:{
                                    'on-change':(value)=>{
                                        if(value!=0){
                                            if(value=="密码"||value=="元数据"||value=="端口转发"){
                                                _this.vmSwitchTypeOperation(params.id,value,params)
                                            }else{
                                                _this.vmSwitchTypeOperation(params.id,value,params)
                                            }
                                        }
                                        $('.falseValue'+params.id).click();
                                        $('.opertionVm .ivu-select-placeholder').text("");
                                    },
                                }
                            },operationOption)])
                        }
                    },
                    {
                        title:'状态',
                        key:'status',
                        align: 'center',
                        minWidth:150,
                        fixed:'right',
                        render:(h,params)=>{
                            let _this = this;
                            params  = params.row;
                            let statusVm ="",fontColor = "",statusLoading = false,ErrorMesage = "";
                            if(_this.vmGroupStatus.length!=0){
                                $.each(_this.vmGroupStatus,function(i,element){
                                    if(element.id==params.id){
                                        if(element.enableCrash){
                                            statusVm  =  "MELT";
                                            ErrorMesage = element.crashMsg;
                                        }else{
                                            statusVm  =  element.status;
                                            ErrorMesage = "";
                                        }
                                        statusLoading = element.loading;
                                        return;
                                    }
                                })
                            }
                            let statusVmGroup = {
                                'ACTIVE':'运行中/#43CD80/false/alRunning.png','Running':'运行中/#43CD80/false/alRunning.png','SHUTOFF':'已关机/#f00/false/alOff.png',
                                'DOWN':'已关机/#f00/false/alOff.png','Stopped':'已停止/#f00/false/alStop.png','SUSPENDED':'已挂起/#f00/false/alSuspend.png',
                                'ERROR':'运行ERROR/#f00/false/runningError.png','PAUSED':'已暂停/#43CD80/false/alPause.png','CRUSH':'运行ERROR/#f00/false/runningError.png',
                                'UNKNOWN':'运行ERROR/#f00/false/runningError.png','powering-off':'关机中/#57a3f3/true','powering-on':'启动中/#57a3f3/true',
                                'rebuilding':'重置中/#57a3f3/true','rebooting_hard':'重启中/#57a3f3/true','suspending':'挂起中/#57a3f3/true',
                                'resuming':'拯救中/#57a3f3/true','pausing':'暂停中/#57a3f3/true','unpausing':'启动中/#57a3f3/true',
                                'MELT':'已崩溃/#f00/false/runningError.png'
                            }
                            if(!statusVmGroup[statusVm]){
                                statusVmGroup[statusVm] = "加载中/#808695/true"
                            }
                            let _iamgeName = statusVmGroup[statusVm].split('/')[2]=='false'?'./static/'+statusVmGroup[statusVm].split('/')[3] :'';
                            return h('div',{
                                style:{
                                    color:statusVmGroup[statusVm].split('/')[1]
                                }
                            },[h('Button',{
                                props:{
                                    type:'default',
                                    loading:statusVmGroup[statusVm].split('/')[2] =="false" ? false :true
                                },
                                attrs:{
                                    title:ErrorMesage,
                                }
                            },[
                                h('span',{
                                    style:{
                                        color:statusVmGroup[statusVm].split('/')[1]
                                    }
                                },
                                    statusVmGroup[statusVm].split('/')[0])
                                ])
                            ])
                        }
                    },
                ],
                vmListDataTable:[],
                tableHeight:'',
                virtualNameOfReach:'',
                virtualIPOfReach:'',
                virtualSystypeOfReach:'',
                virtualKeyOfReach:'',
                virtualValueOfReach:'',
                virtualvmTypeOfReach:'',
                virtualMacOfReach:'',
                virtualImageNameOfReach:'',
                virtualNetworkIdOfReach:'',
                virtualSegmentIdOfReach:'',
                virtualSubnetIdOfReach:'',
                vmKeys:[],
                vmValues:[],
                vmIdGroupStatus:[],
                vmGroupStatus:[],
                vmPassword:'',
                vmId_:'',
                updatePasswordLoading:true,
                tableListHeight:'',
                selectValue:'',
                vmAttributeData:[],
                selectTableDataGroup:[],
                btnData:[],
                setTimeClear:'',
    
                portListPanel:false,
                portTableCloums:[
                    {
                        title:'forwardIP',
                        key:'forwardIp',
                        align:'center'
                    },
                    {
                        title:'forwardPort',
                        key:'forwardPort',
                        align:'center'
                        
                    },
                    {
                        title:'vmIP',
                        key:'vmIp',
                        align:'center'
                    },
                    {
                        title:'vmPort',
                        key:'vmPort',
                        align:'center'
                    },
                    
                    {
                        title:'type',
                        key:'type',
                        align:'center'
                    },
                    {
                        title:'protocal',
                        key:'protocal',
                        align:'center'
                    },
                    {
                        title:'lastExpireTime',
                        key:'lastExpireTime',
                        align:'center'
                    },
                    {
                        title:'createName',
                        key:'userName',
                        align:'center'
                    },
                    {
                        title:'actions',
                        key:'actions',
                        render:(h,params)=>{
                            let _this = this;
                            params = params.row;
                            return h('Poptip',{
                                style:{
    
                                },
                                props:{
                                    confirm:true,
                                    title:"您确定要删除吗？",
                                },
                                on:{
                                    'on-ok':()=>{
                                        _this.deleteVmPort(params.token)
                                    },
                                    'on-cancel':()=>{
    
                                    }
                                }
                            },[h('Button',{
                                style:{
                                    margin:'5px'
                                },
                                props:{
                                    type:'error'
                                },
                            },'删除')])
                        }
                    }
                ],
                portTableData:[],
                openPort:false,
                addPortLoading:true,
                formValidate: {
                    type: 'ssh',
                    port:22,
                    protocol: 'tcp',
                    customType:'customType',
                },
                ruleValidate: {
                    type: [
                        { required: true, message: '请选择类型', trigger: 'change' }
                    ],
                    port: [
                        { required: true, message: '请填写端口', trigger: 'change',type:'number'},
                    ],
                    protocol: [
                         { required: true, message: '请选择协议', trigger: 'change' }
                    ],
                    customType: [
                         { required: true, message: '请输入自定义类型', trigger: 'change' }
                    ]
                },
                disabledType:false,
                disabledprototol:true,
                accessTokenRef :'',
                setTimeoutReach:'',
                networkData:[],
                subnetData:[],
                segmentsData:[],
                refreshIndex:0,
                vmNetworkData:[],
                controlSearchBtn:false,
                controlSearchText:'更多',
                controlSearchImage:'ios-more',
                //接入方式增加选择面板
                selectDataPanel:false,
                selectDataGroup:[],
                selectDataPanelLoading:true,
                accessVmIp:'',
                accessVmId:'',
                accessVmType:'',
                passwordModal:{
                    loading:true,
                    show:false
                }
            }
        },
        created(){
            this.vmCurrentPage = sessionStorage.getItem('vmCurrentPage')?Number(sessionStorage.getItem('vmCurrentPage')):1;
            this.vmItemPage = sessionStorage.getItem('vmItemPage')?Number(sessionStorage.getItem('vmItemPage')):10;
            this.getVmListManage();
            this.getProjectInformation()
        },
        methods:{
            changeIpAccess(value){
                this.accessVmIp = value;
            },
            vmAccessChage(){
                if(!this.accessVmIp){
                    this.$Message.info("请选择一个IP")
                    this.selectDataPanelLoading = false;
                    this.$nextTick(()=>{
                        this.selectDataPanelLoading = true;
                    })
                    return;
                }
                let _this = this;
                axios({
                    url:'netns/access/'+ this.accessVmId+'/'+this.accessVmType,
                    method:'POST',
                    data:{
                        "ip": this.accessVmIp,
                    }
                }).then(function(response){
                    if(response.code==1){
                        _this.accessTokenRef = response.attribute.token
                        window.openTrain(response.attribute.url+'&Authorization='+cookieUse.getCookie('open-token'))
                        _this.selectDataPanelLoading = false;
                        _this.$nextTick(()=>{
                            _this.selectDataPanelLoading = true;
                        })
                    }else{
                        _this.$Message.error({content:response.prompt,closable: true,duration: 10})
                        _this.selectDataPanelLoading = false;
                        _this.$nextTick(()=>{
                            _this.selectDataPanelLoading = true;
                        })
                    }
                })
            },
            controlSearch(){
                if(this.controlSearchBtn){
                    this.controlSearchText = '更多'
                    this.controlSearchImage = 'ios-more'
                }else{
                    this.controlSearchText = '收起'
                    this.controlSearchImage = 'ios-arrow-up'
                }
                this.controlSearchBtn = !this.controlSearchBtn
            },
            getAccountInfo(){
                let _this = this;
                axios({
                    url: '/identity/account/info',
                    method: 'get'               
                    }).then(function (response) {
                    if(response.code != '1'){
                        _this.$Message.warning(response.message);
                    }else{
                        let data = response.data;
                        _this.oUserName = data.nickname;
                        if(data.avatar){
                            _this.$refs.img_user.src=data.avatar;
                        }
                    }
                });
            },
            openPortPanel(){
                this.$refs['formValidate'].resetFields()
                this.openPort = true;
                this.formValidate.type = 'ssh'
                this.formValidate.port = 22
                this.formValidate.protocol = 'tcp'
                this.disabledType = false;
            },
            addPort(){
                let _this = this;
                this.$refs['formValidate'].validate((valid) => {
                    if (valid) {
                        _this.formValidate.type = _this.formValidate.type =="other" ? _this.formValidate.customType :_this.formValidate.type
                        axios({
                            url:'/netns/access/'+_this.vmId_+'/'+_this.formValidate.type,
                            method:'post',
                            data:{
                                "port": _this.formValidate.port,
                                "protocal": _this.formValidate.protocol,
                                "enablePortForward":true
                            }
                        }).then((response)=>{
                            if(response.code==1){
                                _this.reachVmPortsList(_this.vmId_)
                                _this.openPort = false;
                                _this.addPortLoading = false;
                                _this.$nextTick(() => {
                                    _this.addPortLoading = true;
                                });
    
                            }else{
                                _this.$Message.error({content:response.prompt,duration: 10})
                                _this.addPortLoading = false;
                                _this.$nextTick(() => {
                                    _this.addPortLoading = true;
                                });
                            }
                        })
                    } else {
                        _this.addPortLoading = false;
                        _this.$nextTick(() => {
                            _this.addPortLoading = true;
                        });
                    }
                });
            },
            getProjectInformation(){
                let _this = this;
                axios({
                    url:"topo-edit/project/"+_this.currentProjectId
                }).then(function(response){
                    if(response.code==1){
                        _this.projectName = response.attribute.project.projectname;
                    }else{
                        _this.$Message.error({content:response.prompt,duration: 10})
                    }
                })
            },
            cancel(){
    
            },
            SaveMetaData(){
                this.updateVmMetadata(this.vmId_)
            },
            removeMetadata(index){
                this.metadataData.splice(index,1)
            },
            handleAddMetadata(){
                this.metadataData.push({
                    key:'',
                    value:'',
                })
            },
            switchineVmCurrentPage(currentPage){
                sessionStorage.setItem('vmCurrentPage',currentPage)
                this.vmCurrentPage = currentPage;
                this.getVmListManage();
                this.selectTableDataGroup = [];
            },
            switchVmItemPage(itemPage){
                sessionStorage.setItem('vmItemPage',itemPage)
                this.vmItemPage = itemPage;
                this.getVmListManage();
                this.selectTableDataGroup = [];
            },
            getVmListManage(){
                this.refreshIndex = 0;
                let _this = this;
                _this.loadingTable = true;
                let params = {
                    projectId:_this.currentProjectId,
                    pageIndex:_this.vmCurrentPage,
                    pageSize:_this.vmItemPage,
                    sortBy:'name',
                    order:'asc',
                }
                if(_this.virtualNameOfReach){
                    params.name = _this.virtualNameOfReach;
                }
                if(_this.virtualSystypeOfReach){
                    params.sysType = _this.virtualSystypeOfReach;
                }
                if(_this.virtualvmTypeOfReach){
                    params.vmType = _this.virtualvmTypeOfReach;
                }
                if(_this.virtualIPOfReach){
                    params.ipAddress = _this.virtualIPOfReach;
                }
                if(_this.virtualMacOfReach){
                    params.macAddress = _this.virtualMacOfReach;
                }
                if(_this.virtualImageNameOfReach){
                    params.imageName = _this.virtualImageNameOfReach;
                }
                if(_this.virtualNetworkIdOfReach){
                    params.networkId = _this.virtualNetworkIdOfReach;
                }
                axios({
                    url:`topo-edit/deployed/vms`,
                    method:'get',
                    params:params
                }).then(function(response){
                    if(response.code==1){
                        sessionStorage.setItem('vmCurrentPage',_this.vmCurrentPage);
                        _this.vmIdGroupStatus = [];
                        _this.vmTotal = response.data.total;
                        _this.vmListDataTable = response.data.items;
                        _this.vmIdGroupStatus =  response.data.items.map(item=>{
                            return item.id
                        });
                        if(_this.vmIdGroupStatus.length!=0){
                            _this.reachManyVmStatus(_this.vmIdGroupStatus);
                        }
                        _this.loadingTable = false;
                    }else{
                        if(response.code!=-2){
                            _this.$Message.error({content:response.prompt,duration: 10})
                        }
                        _this.loadingTable = false;
                    }
                })
            },
            vmAccess(vmId,accessType){
                let _this = this;
                axios({
                    url:'netns/access/'+vmId+'/'+accessType,
                    method:'POST',
                    data:{
    
                    }
                }).then(function(response){
                    if(response.code==1){
                        _this.accessTokenRef = response.attribute.token
                        window.openTrain(response.attribute.url+'&Authorization='+cookieUse.getCookie('open-token'));
                        _this.loadingTable = false;
                    }else{
                        _this.$Message.error({content:response.prompt,closable: true,duration: 10})
                        _this.loadingTable = false;
                    }
                })
            },
            //操作网络
            operationVm(vmId,action,batch){
                
                let _this = this;
                return axios({
                    url:'topo-control/servers/'+vmId+'/action/'+action,
                    method:'POST'
                }).then(function(response){
                    if(response.code==1){
                        if(batch){
                            // _this.reachManyVmStatusSend(_this.selectTableDataGroup.map(item=>{return item.id}))
                        }else{
                            _this.reachManyVmStatusSend(_this.vmIdGroupStatus)
                        }
                    }else{
                        _this.$Message.error({content:response.prompt,closable: true,duration: 10})
                    }
                })
            },
            //重置
            rebuildVm(vmId,batch){
                let _this = this;
                return axios({
                    url:'topo-control/servers/'+vmId+'/action/rebuild',
                    method:'POST'
                }).then(function(response){
                    if(response.code==1){
                        if(batch){
                        //    _this.reachManyVmStatusSend(_this.selectTableDataGroup.map(item=>{return item.id}))
                        }else{
                            _this.reachManyVmStatusSend(_this.vmIdGroupStatus)
                        }
                    }else{
                        _this.$Message.error({content:response.prompt,closable: true,duration: 10})
                    }
                })
            },
            //重启
            rebootVm(vmId,batch){
                let _this = this;
                return axios({
                    url:'topo-control/servers/'+vmId+'/action/soft_restart?type=HARD',
                    method:'POST'
                }).then(function(response){
                    if(response.code==1){
                        if(batch){
                            // _this.reachManyVmStatusSend(_this.selectTableDataGroup.map(item=>{return item.id}))
                        }else{
                            _this.reachManyVmStatusSend(_this.vmIdGroupStatus)
                        }
                        
                    }else{
                        _this.$Message.error({content:response.prompt,closable: true,duration: 10})
                    }
                })
            },
            vmSwitchTypeOperation(vmId,text,params='',batch=''){
                let _this = this;
                switch (text) {
                    case "关机":
                        _this.operationVm(vmId,'stop',batch)
                        break;
                    case "开机":
                        _this.operationVm(vmId,'start',batch)
                        break;
                    case "重置状态":
                        _this.operationVm(vmId,'reset-state-active',batch)
                        break;
                    case "重启":
                        _this.rebootVm(vmId,batch)
                        break;
                    case "重置":
                        _this.rebuildVm(vmId,batch)
                        break;
                    case "挂起":
                        _this.operationVm(vmId,'suspend',batch)
                        break;
                    case "暂停":
                        _this.operationVm(vmId,'pause',batch)
                        break;
                    case "拯救":
                        _this.operationVm(vmId,'resume',batch)
                        break;
                    case "取消暂停":
                        _this.operationVm(vmId,'unpause',batch)
                        break;
                    case "密码":
                        _this.vmId_ = params.id;
                        _this.vmPassword = "";
                        this.currentVm = params
                        _this.passwordModal.show = true;
                        return;
                    case "元数据":
                        _this.vmMetadata = true;
                        _this.metadataData = [
                            {
                                key:'',
                                value:''
                            }
                        ]
                        _this.reachVmMetaData(params.id)
                        _this.vmName = params.name;
                        _this.vmId_ = params.id;
                        break;
                    case "端口转发":
                        _this.vmName = params.name
                        _this.vmId_ = params.id;
                        _this.portTableData = [];
                        _this.portListPanel = true;
                        _this.reachVmPortsList(params.id)
                        break;
                    default:
                        console.log('不识别命令：'+text)
                        break;
                }
            },
            //查询虚拟机的状态
            reachVmStatus(vmId){
                let _this  =this;
                axios({
                    url:'topo-control/servers/'+vmId+'/status',
    
                }).then(function(response){
                    if(response.code==1){
                        if(response.list[0].taskStatus!="null"){
                            _this.reachVmStatus(vmId);
                        }else{
                            _this.getVmListManage()
                        }
                    }else{
                        if(response.message){
                            _this.$Message.error({content:response.message,closable:true,duration:10})
                        }else{
                            _this.$Message.error({content:response.prompt,closable:true,duration:10})
                        }
                        
                    }
                })
            },
            //批量查询虚拟机状态
            reachManyVmStatus(vmIdGroup){
                let _this  =this;
                axios({
                    url:'topo-control/servers/batch_status',
                    method:"POST",
                    data:vmIdGroup
                }).then(function(response){
                    if(response.code==1){
                        let status_null = [];
                        let vm_status = "",vm_loading = false;
                        _this.vmGroupStatus = response.list.map(item=>{
                            if(item.taskStatus!="null"){
                                status_null.push(item.vmId);
                                vm_status = item.taskStatus
                                vm_loading = true
                            }else{
                                vm_status = item.status
                                vm_loading = false
                            }
                            return {
                                id:item.vmId,
                                status:vm_status,
                                loading:vm_loading,
                                enableCrash:item.enableCrash,
                                crashMsg:item.crashMsg ? item.crashMsg  :'',
                            }
                        });
                        if(status_null.length!=0){
                            console.log(status_null)
                            _this.reachManyVmStatusSend(status_null)
                        }
                        
                    }else{
                        _this.$Message.error({content:response.prompt,closable:true,duration:10})
                    }
                })
            },
            reachManyVmStatusSend(vmIdGroup){
                let _this  =this;
                clearTimeout(_this.setTimeClear)
                axios({
                    url:'topo-control/servers/batch_status',
                    method:"POST",
                    data:vmIdGroup
                }).then(function(response){
                    if(response.code==1){
                        let status_null = [];
                        let status_new = [];
                        let vm_status = "";
                        status_new = response.list.map(item=>{
                            if(item.taskStatus!="null"){
                                status_null.push(item.vmId);
                                vm_status = item.taskStatus
                            }else{
                                vm_status = item.status
                            }
                            return {
                                id:item.vmId,
                                status:vm_status
                            }
                        });
                        _this.vmGroupStatus.forEach(item=>{
                            status_new.forEach(element=>{
                                if(item.id==element.id){
                                    item.status = element.status;
                                }
                            })
                        });
                        if(status_null.length!=0){
                            _this.setTimeClear = setTimeout(() => {
                                _this.reachManyVmStatusSend(status_null)
                            }, 3000);
                        }
                       
                    }else{
                        _this.$Message.error({content:response.prompt,closable:true,duration:10})
                    }
                })
            },
            //批量修改生成随机密码
            updateVmPasswordMany(ele){
                let _this = this;
                let access = ele.accesses[0]
                let data = {
                    id:ele.id,
                    password:_this.getRandomPassword(6),
                    type:access.accessType,
                    username:access.username,
                }
                return axios({
                    url:'topo-control/servers/'+ele.id+'/change-password',
                    method:'post',
                    data:data,
                }).then(function(response){
                    if(response.code==1){
                       
                    }else{
                        _this.$Message.error({content:response.prompt,closable:true,duration:10});
                        
                    }
                })
            },
            getRandomPassword(range){
                let str = "",
                // range = 6,
                arr = [
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
                'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
                'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','0', '1', '2', '3', '4', '5', '6', '7', '8', '9',];
              
                for (let i = 0; i < range; i++) {
                    let pos = Math.round(Math.random() * (arr.length - 1));
                    str += arr[pos];
                }
                return str;
            },
            reachVmMetaData(vmId){
                let _this = this;
                axios({
                    url:'topo-control/servers/'+vmId+'/metadata',
                    method:'get'
                }).then(function(response){
                    if(response.code==1){
                        _this.metadataData = [];
                        let metadata_ = response.attribute.metadata;
                        if(JSON.stringify(metadata_) == "{}"){
                             _this.metadataData.push({
                                    key:'',
                                    value:''
                                })
                        }else{
                            for(let i in metadata_){
                                _this.metadataData.push({
                                    key:i,
                                    value:metadata_[i]
                                })
                            }
                        }
                       
                    }else{
                        _this.$Message.error({content:response.prompt,duration:10,closable:true})
                    }
                })
            },
            updateVmMetadata(vmId){
                let _this = this;
                let objMedata = {};
                _this.metadataData.forEach(element=>{
                    objMedata[element.key] = element.value;
                });
                axios({
                    url:'topo-control/servers/'+vmId+'/metadata',
                    method:'put',
                    data:objMedata
                }).then(function(response){
                    if(response.code==1){
                        _this.$Message.success("保存成功");
                        _this.vmMetadata = false;
                        _this.vmMetadataLoading = false;
                        _this.$nextTick(()=>{
                            _this.vmMetadataLoading = true;
                        })
                    }else{
                        _this.$Message.error({content:response.prompt,closable:true,duration:10});
                        _this.vmMetadataLoading = false;
                        _this.$nextTick(()=>{
                            _this.vmMetadataLoading = true;
                        })
                    }
                })
            },
            deleteVmMetadata(vmId,key){
                let _this = this;
                axios({
                    url:'topo-control/servers/'+vmId+'/metadata/'+key,
                    method:'delete'
                }).then(function(response){
                    if(response.code==1){
                        // _this.
                    }else{
                        _this.$Message.error({content:response.prompt,closable:true,duration:10})
                    }
                })
            },
            //查询虚拟机的key
            getVmAttributeKey(value){
                if(!value){
                    return;
                }
                let _this = this;
                axios({
                    url:'topo-edit/topo/'+_this.currentProjectId+'/attribute/tree?type=VM',
                }).then(function(response){
                    if(response.code==1){
                        if(response.attribute.result!="{}"){
                            _this.vmAttributeData = Object.keys(response.attribute.result).map(item=>{
                                let oneMenu = [
                                   {
                                        label:'--',
                                        value:'--'
                                   }
                                ];
                               
                                return {
                                    value:item,
                                    label:'key：'+item,
                                    children:oneMenu
                                }
                            })
                            console.log(_this.vmKeys)
                        }
                         
                    }else{
                        if(response.code!=-2){
                            _this.$Message.error({content:response.prompt,closable:true,duration:10})
                        }
                    }
                })
            },
            //通过key 查找value
            getValueByVmKey(vmAttributeKey){
                console.log(vmAttributeKey)
                let _this = this;
                _this.vmValues = [];
                _this.virtualValueOfReach = "";
                if(!vmAttributeKey){
                    return;
                }
                axios({
                    url:'topo-edit/topo/'+_this.currentProjectId+'/attribute/key/'+vmAttributeKey,
                }).then(function(response){
                    if(response.code==1){
                        if(response.attribute.result.length!=0){
                            _this.vmValues = response.attribute.result;
                        }
                    }else{
                        _this.$Message.error({content:response.prompt,closable:true,duration:10})
                    }
                })
            },
            listenKeyChange(vmAttributeKey){
                console.log(vmAttributeKey)
                let _this = this;
            
                if(!vmAttributeKey){
                    _this.virtualKeyOfReach = "";
                    _this.virtualValueOfReach = "";
                    return;
                }else{
                    if(vmAttributeKey.length==1){
                        _this.virtualKeyOfReach = vmAttributeKey[0];
                        _this.virtualValueOfReach = "";
                        axios({
                            url:'topo-edit/topo/'+_this.currentProjectId+'/attribute/key/'+vmAttributeKey[0],
                        }).then(function(response){
                            if(response.code==1){
                                if(response.attribute.result.length!=0){
                                    for(let i=0;i< _this.vmAttributeData.length;i++){
                                        if(_this.vmAttributeData[i].value==vmAttributeKey[0]){
                                            _this.vmAttributeData[i].children = [];
                                            response.attribute.result.forEach(element=>{
                                                _this.vmAttributeData[i].children.push({
                                                    label:'value：'+element,
                                                    value:element
                                                })
                                            })
                                            return;
                                        }
                                    }
                                }
                            }else{
                                _this.$Message.error({content:response.prompt,closable:true,duration:10})
                            }
                        });
                    }else{
                        _this.virtualKeyOfReach = vmAttributeKey[0];
                        _this.virtualValueOfReach = vmAttributeKey[1];
                    }
                }
                _this.vmCurrentPage=1;
                sessionStorage.setItem('vmCurrentPage',1)
                _this.getVmListManage();
               
            },
            opeartionManyVm(){
                let _this = this;
                if(this.selectTableDataGroup.length!=0){
                    _this.loadingTable = true;
                  
                    let vmGroupStatus  = [];
                    axios({
                        url:'topo-control/servers/batch_status',
                        method:"POST",
                        data:_this.selectTableDataGroup.map(item=>{return item.id})
                    }).then(function(response){
                        if(response.code==1){
                            let vm_status = "";
                            return vmGroupStatus = response.list.map(item=>{
                                if(item.taskStatus!="null"){
                                    vm_status = item.taskStatus
                                }else{
                                    vm_status = item.status
                                }
                                return vm_status
                            });
                        }else{
                             _this.loadingTable =  false;
                            _this.$Message.error({content:response.prompt,closable:true,duration:10})
                        }
                    }).then(function(vmGroupStatus){
                        _this.vmManyNumber = vmGroupStatus.length;
                        let uniqueArr = [...new Set(vmGroupStatus)];
                         _this.loadingTable =  false;
                        if(uniqueArr.length!=1){
                            _this.$Message.info("您选择的虚拟机中，存在不同状态的虚拟机")
                        }else{
                            _this.vmManyPanel = true;
                            switch (uniqueArr[0]) {
                                case "ACTIVE":
                                    _this.btnData = ["关机","重启","重置","挂起","暂停","修改密码(系统随机生成)"]
                                    break;
                                case "Running":
                                    _this.btnData = ["关机","重启","重置","挂起","暂停","修改密码(系统随机生成)"]
                                    break;
                                case "SHUTOFF":
                                    _this.btnData = ["开机","重置"]
                                    break;
                                case "DOWN":
                                    _this.btnData = ["开机","重置"]
                                    break;
                                case "Stopped":
                                    _this.btnData = ["开机","重置"]
                                    break;
                                case "SUSPENDED":
                                    _this.btnData = ["拯救"]
                                    break;
                                case "ERROR":
                                    _this.btnData = ["重启","重置状态"]
                                    break;
                                case "PAUSED":
                                    _this.btnData = ["取消暂停"]
                                    break;
                                case "CRUSH"://虚拟机奔溃状态
                                    _this.btnData = ["关机","重启"]
                                    break;
                                case "UNKNOWN"://虚拟机未知状态
                                    _this.btnData = []
                                    break;
                                default:
                                    break;
                            }
                        }
                    })
                }else{
                    _this.$Message.info("请选择要操作的虚拟机")
                }
            },
            selectTableData(values){
                this.selectTableDataGroup = values
                // console.log(values)
            },
            testFgm(value){
                this.selectTableDataGroup.forEach(element=>{
                    this.vmSwitchTypeOperation(element.id,value,'',true)
                });
            },
            okVm(value){
                let _this = this;
                let activeFunction = [];
                activeFunction = this.selectTableDataGroup.map(element=>{
                    let vmId = element.id;
                    let batch = true;
                    return new Promise((resolve,reject)=>{
                        switch (value) {
                            case "关机":
                                _this.operationVm(vmId,'stop',batch).then(()=>{
                                    resolve()
                                })
                                break;
                            case "开机":
                                _this.operationVm(vmId,'start',batch).then(()=>{
                                    resolve()
                                })
                                break;
                            case "重启":
                                _this.rebootVm(vmId,batch).then(()=>{
                                    resolve()
                                })
                                break;
                            case "重置":
                                _this.rebuildVm(vmId,batch).then(()=>{
                                    resolve()
                                })
                                break;
                            case "挂起":
                                _this.operationVm(vmId,'suspend',batch).then(()=>{
                                    resolve()
                                })
                                break;
                            case "暂停":
                                _this.operationVm(vmId,'pause',batch).then(()=>{
                                    resolve()
                                })
                                break;
                            case "拯救":
                                _this.operationVm(vmId,'resume',batch).then(()=>{
                                    resolve()
                                })
                                break;
                            case "取消暂停":
                                _this.operationVm(vmId,'unpause',batch).then(()=>{
                                    resolve()
                                })
                                break;
                            case "修改密码(系统随机生成)":
                                _this.updateVmPasswordMany(element).then(()=>{
                                    resolve()
                                })
                                
                                break;
                            default:
                                break;
                        }
                    });
                    // return this.vmSwitchTypeOperation(element.id,value,'',true)
                });
            
                this.vmManyPanel = false;
                Promise.all(activeFunction).then(()=>{
                    // console.log('----------');
                    _this.getVmListManage();
                    // _this.reachManyVmStatusSend(_this.vmIdGroupStatus);
                })
                return;
                
            },
            test(value){
            },
            reachVmPortsList(vmId){
                let _this = this;
                _this.portTableData = [];
                return axios({
                    url:'netns/access/detail?vmId='+vmId,
                    method:'get',
                    
                }).then((response)=>{
                    if(response.code==1){
                        $.each(response.attribute.result.pageData,function(i,item){
                            if(item.forwardIp){
                                _this.portTableData.push(item)
                            }
                        })
                        
                    }else if(response.code==-2){
                        _this.portTableData = [];
                    }else{
                        _this.$Message.error({content:response.prompt,duration: 10})
                    }
                })
            },
            deleteVmPort(token){
                let _this = this;
                axios({
                    url:'/netns/access/tokens/'+token,
                    method:'delete'
                }).then((response)=>{
                    if(response.code==1){
                        _this.reachVmPortsList(this.vmId_);
                    }else{
                        _this.$Message.error({content:response.prompt,duration: 10})
                    }
                })
            },
            listenTypeChange(value){
                console.log(value)
                let _this = this;
                _this.disabledprototol = true
                _this.disabledType = true
                switch (value) {
                    case "ssh":
                        _this.formValidate.port = 22
                        _this.formValidate.protocol = "tcp"
                        _this.disabledType = false
                        _this.formValidate.customType = 'test'
                        break;
                    case "rdp":
                        _this.formValidate.port = 3389
                        _this.formValidate.protocol = "tcp"
                        _this.disabledType = false
                        _this.formValidate.customType = 'test'
                        break;
                    case "vnc":
                        _this.formValidate.port = 5901
                        _this.formValidate.protocol = "tcp"
                        _this.disabledType = false
                        _this.formValidate.customType = 'test'
                        break;
                    case "other":
                        // _this.formValidate.port = 22
                        _this.disabledprototol = false
                        _this.disabledType = true
                        _this.formValidate.port = 1;
                        _this.formValidate.customType = ''
                        break;
                    default:
                        break;
                }
            },
            deleteAccessAisle(vmId){
                let _this = this;
                axios({
                    url:'netns/access/vms/'+vmId,
                    method:'delete'
                }).then((response)=>{
                    if(response.code==1){
                        _this.$Message.success("刷新成功")
                        _this.loadingTable = false;
                    }else{
                        _this.$Message.warning(response.prompt)
                        _this.loadingTable = false;
                    }
                })
            },
            limitingReach(){
                let _this = this;
                clearTimeout(_this.setTimeoutReach);
                _this.setTimeoutReach = setTimeout(() => {
                    _this.getVmListManage()
                }, 500);
            },
            reachNetworkList(value){
                if(!value){
                    return
                }
                let _this = this;
                axios({
                    url:'topo-edit/topo/project/'+_this.currentProjectId+'/tree',
                    method:'GET',
                    data:"NW",
                }).then(function(response){
                    if(response.code==1){
                        _this.networkData = []
                        let networkDataTree = response.data;
                        function getNetwork(currentNetworkData){
                            _this.networkData.push({
                                networkName:currentNetworkData.name,
                                networkId:currentNetworkData.id
                            })
                            if(currentNetworkData.networks&&currentNetworkData.networks.length!=0){
                                for(let i = 0;i<currentNetworkData.networks.length;i++){
                                    getNetwork(currentNetworkData.networks[i])
                                }
                            }
                        }
                        getNetwork(networkDataTree)
                        console.log(_this.networkData)
                    }else{
                        _this.$Message.error({content:response.prompt,duration: 10})
                    }
                })
            },
            reachSubnetList(value){
                if(!value){
                    return
                }
                let _this = this;
                axios({
    //              url:'deploy/project/subnets?projectId='+_this.currentProjectId+'&page=1&rows=20000',
                    url:`topo-edit/deployed/projects/${_this.currentProjectId}/subnets`+'&pageIndex=1&pageSize=20000',
                    method:'GET',
                }).then(function(response){
                    if(response.code==1){
                        
                        _this.subnetData = response.data.items;
                    }else{
                        _this.$Message.error({content:response.prompt,duration: 10})
                    }
                })
            },
            reachSegmentList(value){
                console.log(value);
                if(!value){
                    return
                }
                let _this = this;
                axios({
    //              url:'deploy/project/segments?projectId='+_this.currentProjectId+'&page=1&rows=20000',
                    url:`topo-edit/deployed/projects/${_this.currentProjectId}/segments`+'&pageIndex=1&pageSize=20000',
                    method:'GET',
                }).then(function(response){
                    if(response.code==1){
                        
                        _this.segmentsData = response.data.items;
                    }else{
                        _this.$Message.error({content:response.prompt,duration: 10})
                    }
                })
            },
            changePassword(){
                let _this = this;
                if(!_this.vmPassword){
                    _this.$Message.info("请填写密码")
                    _this.loading = false;
                    _this.passwordModal.loading = false;
                    setTimeout(() => {
                        _this.passwordModal.loading = true;
                    }, 500);
                    return;
                }
                let myPromis = this.cloudType !== 'h3c'
                ? axios({
                    url:`topo-control/servers/${_this.vmId_}/admin-password?pwd=${_this.vmPassword}`,
                    method:'put'
                })
                : axios({
                    url:'topo-control/servers/'+this.currentVm.id+'/change-password',
                    method:'post',
                    data: {
                        id: this.currentVm.id,
                        password: this.vmPassword,
                        "type": "qga",
                        username: this.currentVm.accesses[0].username,
                    },
                })
                myPromis.then(function(response){
                    if(response.code==1){
                        _this.$Message.success("修改成功")
                        _this.getVmListManage();
                       
                    }else{
                        _this.$Message.error({content:response.prompt || response.message,closable:true,duration:10});
                       
                    }
                    _this.passwordModal.loading = false;
                    setTimeout(() => {
                        _this.passwordModal.loading = true;
                    }, 500);
                })
            }
        },
        watch:{
            vmListDataTable:{
                handler(newName, oldName){
                   
                },
                immediate: true
            }
        },
        
    }
</script>
    
<style>
    .headerBtn1{
        text-align: left;
        margin:15px 0;
    }
    .pageStyle1{
        text-align: center;
        margin-top:10px;
    }
    .operation .ivu-select-arrow{
        right: 2px
    }
    .operation .ivu-select-selection{
        border-radius: 0px 4px 4px 0px !important;
    }
    .accessType .ivu-select-arrow{
        right: 2px
    }
    .accessType .ivu-select-selection{
        border-radius: 0px 4px 4px 0px !important;
    }
    .opertionVm .ivu-select-arrow{
        right: 2px
    }
    .opertionVm .ivu-select-selection{
        border-radius: 0px 4px 4px 0px !important;
    }
    .ivu-table-wrapper{
        overflow: visible !important
    }
    .ivu-tag-border.ivu-tag-closable .ivu-icon-ios-close{
        top: -2px;
    }
    .ivu-table-tip{
        overflow: hidden !important;
    }
    .expendSpanStyle{
        display: inline-block;
        margin-right: 25px;
        min-width: 300px;
    }
    #vmListTable .ivu-table-overflowX{
        overflow: auto;
    }
</style>